package com.interceptor;

import com.alibaba.fastjson.JSON;
import com.constants.RedisConst;
import com.util.BussiEnum;
import com.util.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author chl
 * @Description 拦截器 -- 登录
 * @Date 9:21 2022/1/4
 **/
@Slf4j
public class ApiInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String token = request.getHeader("token");
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter pw = response.getWriter();
        if (StringUtils.isBlank(token)) {
            outPrint(pw, createJsonObject("请登录后再操作", BussiEnum.TOKEN_USELESS.getCode(), null));
            return false;
        }

        String loginInfo = stringRedisTemplate.opsForValue().get(RedisConst.USER_LOGIN_INFO + token);
        if (StringUtils.isBlank(loginInfo)) {
            outPrint(pw, createJsonObject("请登录后再操作", BussiEnum.TOKEN_USELESS.getCode(), null));
            return false;
        }

//        UserInfoVo userInfoVo = JSONObject.parseObject(loginInfo, UserInfoVo.class);
//        if (Objects.isNull(userInfoVo)) {
//            outPrint(pw, createJsonObject("请登录后再操作", BussiEnum.TOKEN_USELESS.getCode(), null));
//            return false;
//        }

//        String status = stringRedisTemplate.opsForValue().get(RedisConst.USER_LOGIN_INFO + userInfoVo.getUserId());

//        UserStatusVo userStatusVo = null;
//        if (StringUtils.isNotBlank(status)) {
//
//            userStatusVo = JSON.parseObject(status, UserStatusVo.class);
//
//        } else {
//            userStatusVo = new UserStatusVo();
//            UserInfoVo userAccountInfo = accountService.getUserAccountInfo(userInfoVo.getUserId(), "", "");
//            if (userAccountInfo == null) {
//                outPrint(pw, createJsonObject("该账号已被删除或禁用", BussiEnum.TOKEN_USELESS.getCode(), null));
//                return false;
//            }
//            CoRole role = roleService.getCoRoleByUuid(null, userInfoVo.getRoleId());
//            if (null == role || role.getRoleStatus().equals(0)) {
//                stringRedisTemplate.delete(token);
//                outPrint(pw, createJsonObject("账号角色已被删除或禁用", BussiEnum.TOKEN_USELESS.getCode(), null));
//            }
//            userStatusVo.setAccountStatus(userAccountInfo.getAccountStatus());
//            userStatusVo.setRoleStatus(role.getRoleStatus());
//        }
//
//        if (userStatusVo.getAccountStatus().equals(0)) {
//            outPrint(pw, createJsonObject("账号已被禁用", BussiEnum.TOKEN_USELESS.getCode(), null));
//            stringRedisTemplate.delete(token);
//            return false;
//        }
//
//        if (Objects.isNull(userStatusVo) || StatusEnum.FORBIDDEN.getCode().equals(userStatusVo.getRoleStatus())) {
//            outPrint(pw, createJsonObject("账号已被禁用", BussiEnum.TOKEN_USELESS.getCode(), null));
//            stringRedisTemplate.delete(token);
//            return false;
//        }
//
//        CoEnterprise enterprise = enterpriseService
//                .getOne(new LambdaQueryWrapper<CoEnterprise>()
//                        .eq(CoEnterprise::getUuid, userInfoVo.getCompanyId()));
//        if (null == enterprise) {
//            outPrint(pw, createJsonObject("企业不存在", BussiEnum.TOKEN_USELESS.getCode(), null));
//            stringRedisTemplate.delete(token);
//            return false;
//        }
//
//        if (enterprise.getEnterpriseStatus() != 1) {
//            outPrint(pw, createJsonObject("企业已被禁用,暂无法登录", BussiEnum.TOKEN_USELESS.getCode(), null));
//            stringRedisTemplate.delete(token);
//            return false;
//        }
//
//        if (StringUtil.isNotBlank(userInfoVo.getMobile())) {
//            String userInfoJudgeForIfDelete = stringRedisTemplate.opsForValue().get(RedisConst.USER_STATUS + userInfoVo.getAccountId());
//            if (StringUtils.isBlank(userInfoJudgeForIfDelete)) {
//                if (userService.checkIfHistoryUserExitsByMobile(userInfoVo.getMobile())) {
//                    outPrint(pw, createJsonObject("该账号已被删除或禁用", BussiEnum.TOKEN_USELESS.getCode(), null));
//                } else {
//                    outPrint(pw, createJsonObject("请登录后再操作", BussiEnum.TOKEN_USELESS.getCode(), null));
//                }
//                return false;
//            }
//        }

        // 获取超管角色ID
//        if (StringUtil.isNotBlank(userInfoVo.getCompanyId())) {
//            CoAccount one = accountService.getOne(new QueryWrapper<CoAccount>()
//                    .eq("account_type", 0)
//                    .eq("company_id", userInfoVo.getCompanyId()));
//            request.setAttribute("superRoleId", one.getRoleId());
//        }

        //用户信息
//        request.setAttribute("loginAccountInfo", userInfoVo);

        return true;
    }

    /**
     * 后处理回调方法，实现处理器（controller）的后处理，但在渲染视图之前
     * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    /**
     * 整个请求处理完毕回调方法，即在视图渲染完毕时回调，
     * 如性能监控中我们可以在此记录结束时间并输出消耗时间，
     * 还可以进行一些资源清理，类似于try-catch-finally中的finally，
     * 但仅调用处理器执行链中
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }

    private void outPrint(PrintWriter out, Response response) {
        out.print(JSON.toJSONString(response));
    }

    public Response createJsonObject(String msg, int errorCode, Object data) {
        return Response.createError(msg, errorCode, data);
    }

}
